package helper

import (
	viper2 "github.com/spf13/viper"
	"strings"
	"github.com/pkg/errors"
	"fmt"
)

const(
	Config_Home = "./configs/"
	Hosts_Path = "hosts.toml"
)

func ResolveHosts() (string, string, int, map[string]string, error){
	viper := viper2.New()
	viper.SetConfigType("toml")
	viper.SetConfigFile(Config_Home + Hosts_Path)
	err := viper.ReadInConfig()
	if err != nil {
		panic(fmt.Errorf("Fatal error config file: %s \n", err))
	}
	selfInfo := viper.GetString("selfInfo")
	selfID := viper.GetInt("selfID")
	self := viper.GetString("self")
	remotes := make(map[string]string)
	array := viper.GetStringSlice("remotes")
	for _,str := range array {
		item := strings.Split(str, " ")
		if len(item) != 2 {
			return selfInfo, self, selfID, remotes, errors.New("config parse error, remotes format wrong")
		}
		remotes[item[0]] = item[1]
 	}
 	viper = nil
 	return selfInfo, self, selfID, remotes, nil
}

func ResolveIdentity(viper *viper2.Viper) [2]bool {
	isProposer := viper.GetBool("proposer")
	isAcceptor := viper.GetBool("acceptor")
	return [2]bool{isProposer, isAcceptor}
}
